<template>
  <view class="min-h-[100vh]" :style="themeColor()">

    <!-- 顶部图片 -->
    <view class="rank-head w-[100%] h-[344rpx]" :style="headerStyle">
      <view class="text-[40rpx] text-[#fff] absolute top-[200rpx]  left-[40rpx]">
        <text v-if="state.position">您目前的排名:{{ state.position }}名</text>
        <text v-else>您目前暂无排名</text>

      </view>
    </view>
    <view class="tab-style-3 pt-[4rpx] bg-[#fff]">
      <view class="tab-items"
        :class="{ '!text-primary class-select': fromType.account_data_gt === item.account_data_gt }"
        v-for="(item, index) in rankList" :key="index" @click="fromTypeFn(item, index)">{{ item.name }}
      </view>
    </view>
    <view class="rank-list p-[20rpx] relative ">

      <!-- 列表 -->
      <mescroll-body ref="mescrollRef" :height="listHeight" @init="mescrollInit" :down="{ use: false }"
        @up="getRankGoodsListFn">
        <view class="bg-[#fff] flex rounded-[var(--rounded-mid)] p-[20rpx]" v-for="(item, index) in rankGoodsList"
          :key="item.goods_id" :class="{ 'mb-[20rpx]': (rankGoodsList.length - 1) != index }"
          v-if="rankGoodsList.length">
          <view class="w-[120rpx] h-[120rpx] flex items-center justify-center relative">
            <!-- 榜单排名图片 -->
            <image v-if="index < 5" class="absolute top-[7rpx] left-[10rpx] w-[50rpx] h-[58rpx]" :style="{ zIndex: 9 }"
              :src="getRankBadge(item.rank_num)" mode="aspectFill"></image>
            <view class="absolute top-[15rpx] left-[10rpx] flex items-center justify-center w-[50rpx] h-[50rpx]"
              v-if="index < 5" :style="{ zIndex: 10 }">
              <text class="text-[24rpx] font-bold text-[#fff]">{{ index + 1 }}</text>
            </view>

            <image class="w-[125rpx] h-[125rpx] rounded-[var(--rounded-mid)]" :src="img(item.avatar)"
              :mode="'aspectFill'" @error="item.avatar = 'static/resource/images/default_headimg.png'">
            </image>
          </view>
          <view class="flex flex-col flex-1 justify-between ml-[20rpx] pt-[4rpx]">
            <view class="text-[28rpx] text-[#333] leading-[40rpx] multi-hidden mb-[10rpx]">
              {{ item.nickname }}
            </view>
            <view class="flex items-center justify-between">
              <view class="text-[var(--price-text-color)] price-font flex items-baseline">
                <text class="text-[24rpx] font-500">￥</text>
                <text class="text-[40rpx] font-500">{{ fen2yuan(item.brokeragePrice) }}</text>
              </view>

            </view>
          </view>
        </view>
        <mescroll-empty v-if="!rankGoodsList.length && loading" :option="{ tip: '暂无排行', }"
          @emptyclick="redirect({ url: '/addon/shop/pages/goods/list' })"></mescroll-empty>
      </mescroll-body>


    </view>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from 'vue'
import { redirect, img, pxToRpx } from '@/utils/common';
import { getBrokerageUserChildSummaryPageByPrice, getRankByPrice } from './../api/commission'
import MescrollBody from '@/components/mescroll/mescroll-body/mescroll-body.vue';
import useMescroll from '@/components/mescroll/hooks/useMescroll.js';
import MescrollEmpty from '@/components/mescroll/mescroll-empty/mescroll-empty.vue'
import { onLoad, onPageScroll, onReachBottom } from '@dcloudio/uni-app';
import useDiyStore from '@/app/stores/diy';
import { topTabar } from '@/utils/topTabbar'
import { fen2yuan, timeFormat } from '@/utils/formatting';

const { mescrollInit, downCallback, getMescroll } = useMescroll(onPageScroll, onReachBottom);
const mescrollRef = ref(null);
const loading = ref<boolean>(false);
// 获取系统状态栏的高度
let menuButtonInfo: any = {};
// 如果是小程序，获取右上角胶囊的尺寸信息，避免导航栏右侧内容与胶囊重叠(支付宝小程序非本API，尚未兼容)
// #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO || MP-QQ
menuButtonInfo = uni.getMenuButtonBoundingClientRect();
// #endif


// 获取系统信息
const systemInfo = uni.getWindowInfo();
const topImageHeight = 450;
const screenHeight = systemInfo.windowHeight;
// 将屏幕高度转换为 rpx
const screenHeightInRpx = (screenHeight / systemInfo.screenWidth) * 750;
// 计算列表高度
const listHeight = computed(() => {
  const listHeightValue = screenHeightInRpx - topImageHeight;
  return `${listHeightValue}rpx`;
});

const fromType = ref({
  account_data_gt: 0,
  times: []
})

const rankList = ref<Array<any>>([{ name: '周排行', account_data_gt: 0 }, { name: '月排行', account_data_gt: 1 }]);
const rankGoodsList = ref<Array<any>>([]);

// TODO 芋艿：此处可考虑抽离
/**
 * 获得当前周的开始和结束时间
 */
function getWeekTimes() {
  const today = new Date();
  const dayOfWeek = today.getDay();
  return [
    new Date(today.getFullYear(), today.getMonth(), today.getDate() - dayOfWeek, 0, 0, 0),
    new Date(
      today.getFullYear(),
      today.getMonth(),
      today.getDate() + (6 - dayOfWeek),
      23,
      59,
      59,
    ),
  ];
}

/**
 * 获得当前月的开始和结束时间
 */
function getMonthTimes() {
  const today = new Date();
  const year = today.getFullYear();
  const month = today.getMonth();
  const startDate = new Date(year, month, 1, 0, 0, 0);
  const nextMonth = new Date(year, month + 1, 1);
  const endDate = new Date(nextMonth.getTime() - 1);
  return [startDate, endDate];
}
function formatDate(date) {
  return timeFormat(date, 'yyyy-mm-dd hh:MM:ss');
}
function calculateTimes() {
  let times;
  if (fromType.value.account_data_gt === 0) {
    times = getWeekTimes();
  } else {
    times = getMonthTimes();
  }
  fromType.value.times = [formatDate(times[0]), formatDate(times[1])];
}


// 类型搜索
const fromTypeFn = (data: any, index: number) => {
  fromType.value.account_data_gt = data.account_data_gt
  rankGoodsList.value = []
  calculateTimes();
  getMescroll().resetUpScroll();
}



//获取佣金排行榜
const getRankGoodsListFn = (mescroll: any) => {
  if (rankList.value.length == 0) return;
  loading.value = false;
  let data: object = {
    pageNo: mescroll.num,
    pageSize: mescroll.size,
    times: fromType.value.times
  };

  getBrokerageUserChildSummaryPageByPrice(data).then((res: any) => {
    let newArr = res.data.list;
    //设置列表数据
    if (mescroll.num == 1) {
      rankGoodsList.value = []; //如果是第一页需手动制空列表
    }
    rankGoodsList.value = rankGoodsList.value.concat(newArr);



    loading.value = true;
  }).catch(() => {
    loading.value = true;
    mescroll.endErr(); // 请求失败, 结束加载
  })
}
// 获取排名 
const state = reactive({
  position: 0, // 排名
});

const getBrokerageRankNumberFn = async () => {
  let param: object = {

    times: fromType.value.times
  };
  const {
    code,
    data
  } = await getRankByPrice(param);
  if (code !== 0) {
    return;
  }
  state.position = data;
}
const headerStyle = computed(() => {
  return {
    backgroundImage: 'url(' + img('https://files.meton.vip/22d91bdf84e3c25be9c41ce2c761111fd83e53ad1bd324055e59f10103a7a22e.jpg') + ') ',
    backgroundSize: 'cover',
    backgroundRepeat: 'no-repeat',
    backgroundPosition: 'bottom',
    // paddingTop:Object.keys(menuButtonInfo).length?(Number(menuButtonInfo.height) * 2 + menuButtonInfo.top * 2 + 77)+'rpx':'77rpx',
  }
})

// 获取排行榜名次图片的函数
function getRankBadge(sort: any) {
  switch (sort) {
    case 1:
      return img('addon/shop/rank/rank_first.png');
    case 2:
      return img('addon/shop/rank/rank_second.png');
    case 3:
      return img('addon/shop/rank/rank_third.png');
    default:
      return img('addon/shop/rank/rank.png');
  }
}

onLoad(async (option: any) => {
  calculateTimes()
  getBrokerageRankNumberFn()
})

</script>

<style lang="scss" scoped>
@import '@/addon/shop/styles/common.scss';

.rank-head {
  position: relative;


  .content-box {
    width: 100%;
    position: absolute;
    top: 227rpx;

    .category-slider {
      width: 95%;
      margin: 0 auto;
      line-height: 100rpx;
      white-space: nowrap;
      flex-direction: row;
      justify-content: center;
      align-items: center;

      .category-con {
        width: 100%;
        display: flex;
        align-items: center;

        .category-btn {
          display: inline-block;
          padding: 0 20rpx;
          height: 55rpx;
          text-align: center;
          line-height: 55rpx;
          justify-content: center;
          align-items: center;
          border-radius: 40rpx;
          font-size: 24rpx;
          margin-right: 20rpx;
        }
      }

    }

    // 	.content {
    // 		display: flex;
    // 		justify-content: center;
    // 		align-items: center;
    // 		border-radius: 30rpx;
    // 		padding: 0 20rpx;
    // 		height: 44rpx;
    // 		font-size: 26rpx;
    // 		color: var(--primary-color);
    // 		background: linear-gradient(to right, #FFEBD7, #FFFFFF, #FFEBD7);
    // }
  }

}

.rank-list {
  background: #F8F8F8;
  border-radius: 34rpx 34rpx 0 0;

  .bank-buying {
    width: 100rpx;
    height: 44rpx;
    border-radius: 10rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 24rpx;
    color: #FFFFFF;
    line-height: 44rpx;
    text-align: center;
  }
}
</style>
